package com.nx.run.shopify.config.exception;

import com.nx.common.exception.BusinessException;
import com.nx.common.result.R;
import com.nx.common.result.RStateEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public R<String> handleException(Exception e, HttpServletRequest request) {
        log.error("全局异常拦截器，异常堆栈：", e);

        if (e instanceof IllegalArgumentException) {
            return R.failure(RStateEnum.PARAMS_ERROR.getCode(), RStateEnum.PARAMS_ERROR.getMsg(), e.getMessage());
        }
        // 业务异常
        else if (e instanceof BusinessException) {
            return R.failure(RStateEnum.BUSINESS_ERROR.getCode(), RStateEnum.BUSINESS_ERROR.getMsg(), e.getMessage());
        }
        // 业务异常
        else if (e instanceof NullPointerException) {
            return R.failure(RStateEnum.SYSTEM_ERROR.getCode(), RStateEnum.SYSTEM_ERROR.getMsg(), "系统发生空指针异常");
        }

        return R.failure(RStateEnum.SYSTEM_ERROR.getCode(), RStateEnum.SYSTEM_ERROR.getMsg(), e.getMessage());
    }

}
